const fs = require('fs')
const path = require('path')

// return random base64 str
function randomString(len) {
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var random = Array.from(
    {length: len}, () => {
        return possible[Math.floor(Math.random() * possible.length)]
    }
    ).join('')

     return random
}

// some special language char to common english char
function slugify(str) {
    str = str.replace(/^\s+|\s+$/g, '');
    str = str.toLowerCase();
    var from = "áäâàãåăčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšșťțúůüùûýÿžþÞĐđßÆa·/_,:;";
    var to = "aaaaaaacccdeeeeeeeeiiiinnooooooorrssttuuuuuyyzbBDdBAa------";
    for (let i = 0; i < from.length; i++) {
      str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }
  
    str = str.replace(/[^a-z0-9 -]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-');
  
    return str;
}

// remove folder recursively if not in keepList
function clearFolder(path, keepList) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(file => {
            if (keepList && keepList.includes(file))
                return
            var curPath = path + "/" + file

            if (fs.lstatSync(curPath).isDirectory()) {
                clearFolder(curPath)
                fs.rmdirSync(curPath)
            }
            else {
                fs.unlinkSync(curPath)
            }
        })
    }
}

// recursively copy file, copy direction: `from` -> `to`
function copyFolderSync(from, to) {
    fs.mkdirSync(to, {recursive: true})
    fs.readdirSync(from).forEach(elem => {
        var lstat = fs.lstatSync(path.join(from, elem))
        if (lstat.isDirectory()) {
            copyFolderSync(path.join(from, elem), path.join(to, elem))
        }
        else {
            fs.copyFileSync(path.join(from, elem), path.join(to, elem))
        }
    })
}

// check if the file is textfile as human readable
function isTextFile(filepath) {
    var pathObj = path.parse(filepath)
    if (['.txt', '.md', '.asc', '.csv', '.xml', '.text', '.yml', '.yaml']
        .includes(pathObj.ext)
    ) return true

    return false
}

// get current application version
function getVersion() {
    var version = "";
    var pjson = null

    try {
        pjson = require("../package.json")
    }
    catch {
        return version // empty ""
    }

    const pversion = pjson.version

    version = pversion ? `blog_builder, version: ${pversion}` : "blog_builder version: empty"

    return version
}

// this module functions expose
module.exports = {
    randomString,
    slugify,
    clearFolder,
    copyFolderSync,
    isTextFile,
    getVersion
}